/* *******************************************************************
 *  Music.cpp
 *  CheeseBurgerParadise
 *  Music Player
 *  Credit: this code is based on 
 *    http://www.devmaster.net/articles/openal-tutorials/lesson1.php
 * *******************************************************************
 */

#include "Music.h"

// initialize static variables
ALuint MusicPlayer::Buffer;
ALuint MusicPlayer::Source;


bool MusicPlayer::openWAVFile(const char * filename)
{
	// Position of the source sound.
	ALfloat SourcePos[] = { 0.0, 0.0, 0.0 };

	// Velocity of the source sound.
	ALfloat SourceVel[] = { 0.0, 0.0, 0.0 };


	// Position of the listener.
	ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 };

	// Velocity of the listener.
	ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 };

	// Orientation of the listener. (first 3 elements are "at", second 3 are "up")
	ALfloat ListenerOri[] = { 0.0, 0.0, -1.0,  0.0, 1.0, 0.0 };

    // Variables to load into.
    ALenum format;
    ALsizei size;
    ALvoid* data;
    ALsizei freq;
    ALboolean loop;

    // Load wav data into a buffer.
    alGenBuffers(1, &Buffer);
    if (alGetError() != AL_NO_ERROR)
        return AL_FALSE;

	char * ncFilename = (char *) filename;
    //alutLoadWAVFile(ncFilename, &format, &data, &size, &freq, &loop);
    alutLoadWAVFile(ncFilename, &format, &data, &size, &freq);
    alBufferData(Buffer, format, data, size, freq);
    alutUnloadWAV(format, data, size, freq);
	
	// Bind buffer with a source.
    alGenSources(1, &Source);

    if (alGetError() != AL_NO_ERROR) {
        return false;
	}

    alSourcei (Source, AL_BUFFER,   Buffer   );
    alSourcef (Source, AL_PITCH,    1.0f     );
    alSourcef (Source, AL_GAIN,     1.0f     );
    alSourcefv(Source, AL_POSITION, SourcePos);
    alSourcefv(Source, AL_VELOCITY, SourceVel);
//    alSourcei (Source, AL_LOOPING,  loop     );

    // Do another error check and return.
    if (alGetError() != AL_NO_ERROR) {
        return false;
	}

    alListenerfv(AL_POSITION,    ListenerPos);
    alListenerfv(AL_VELOCITY,    ListenerVel);
    alListenerfv(AL_ORIENTATION, ListenerOri);
    
	return true;

}

bool MusicPlayer::playSound()
{
	alSourcePlay(Source);
	return alGetError() == AL_NO_ERROR;
}

bool MusicPlayer::stopSound()
{
	alSourceStop(Source);
	return alGetError() == AL_NO_ERROR;
}

void MusicPlayer::init(int & argc, char ** argv)
{
	alutInit(&argc, argv);
	alGetError();
}

void MusicPlayer::killAllData()
{
    alDeleteBuffers(1, &Buffer);
    alDeleteSources(1, &Source);
    alutExit();

}
